import os

import click
from flask import Flask, render_template
from flask_cors import CORS
from flask_mail import Message

from tzq.aaa import aaa_bp
from tzq.auth import auth_bp
from tzq.config import DevelopmentConfig
from tzq.config import ProductionConfig
from tzq.config import config
from tzq.data_migration_platform import dmp_bp
from tzq.database_compare_system import dcs_bp
from tzq.database_compare_system.models.JobTableColumnRepare import *
from tzq.database_compare_system.models.dcs_common_models import *
from tzq.database_compare_system.models.dcs_task_models import *
from tzq.document_management_system import dms_bp
from tzq.document_management_system.model.catalog_model import *
from tzq.document_management_system.model.function_model import *
from tzq.document_management_system.model.log_model import *
from tzq.document_management_system.model.lookup_model import *
from tzq.document_management_system.model.message_model import *
from tzq.document_management_system.model.permission_model import *
from tzq.document_management_system.model.property_model import *
from tzq.document_management_system.model.role_model import *
from tzq.extensions import db, mail, scheduler
from tzq.flask_sqlalchemy_postgresql_layui.fspl_commands import register_fspl_commands
from tzq.flask_sqlalchemy_postgresql_layui.fspl_views import fspl_bp
from tzq.flask_sqlalchemy_postgresql_layui_crud.fspl_crud_app import fspl_crud_bp
from tzq.sql_file_analysis_tool import sfat_bp
from tzq.tpc_db_info.tpc_db_info_commands import register_tpc_db_info_commands
from tzq.tpc_db_info.tpc_db_info_views import tpc_db_info_bp
from tzq.util.DateTool import DateTool
from tzq.util.ExecuteBatchSQLScripts import ExecuteBatchSQLScripts
from tzq.util.OpenGaussSQLExecutor2 import SQLScriptExecutor


def create_app(config_name=None):
    # if config_name is None:
    #     config_name = os.getenv('FLASK_CONFIG', 'development')
    # app = Flask(__name__)
    # app = Flask('tzq')
    # app.config.from_object(config[config_name])
    app = Flask(__name__, instance_relative_config=True)
    CORS(app)  # 允许所有来源的跨域请求
    app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev')
    # app.config.from_object(DevelopmentConfig)
    app.config.from_object(ProductionConfig)

    @app.route('/')
    def home():
        # return 'Home Page - <a href="/auth/login">Login</a> | <a href="/auth/profile">profile</a>'
        return render_template('index.html')

    @app.route('/test')
    def test():
        # return 'Home Page - <a href="/auth/login">Login</a> | <a href="/auth/profile">profile</a>'
        return render_template('test.html')

    @scheduler.task("interval", id="do_job_1", hours=2)
    @app.route('/send-email')
    def send_email():
        try:
            date_string = DateTool.format_datetime()
            subject_string = "Flask邮件测试-" + date_string
            # 创建邮件对象
            msg = Message(
                subject=subject_string,  # 邮件主题
                sender='949819874@qq.com',
                recipients=["tttzzzqqq@qq.com"],  # 收件人列表
                body="这是一封来自Flask应用的测试邮件！",  # 邮件正文(纯文本)
                html="<b>HTML格式内容</b><p><h1>这是一封HTML格式的邮件</h1></p>"  # HTML格式内容(可选)
            )
            # 添加附件 (可选)
            with app.open_resource("E:/test/flask.png") as fp:
                msg.attach("image.png", "image/png", fp.read())
            # 发送邮件
            with app.app_context():
                mail.send(msg)
            print("邮件发送成功！", subject_string)
            return "邮件发送成功！"
        except Exception as e:
            return f"邮件发送失败: {str(e)}"

    # @scheduler.task("interval", id="do_job_1", seconds=10)
    # def job1():
    #     print("Job 1 is running.")

    # # 定义要定期调用的函数
    # def call_api():
    #     response = requests.get('http://example.com/api')
    #     print("API called at", response.text)

    """ 注册扩展 """
    register_extensions(app)

    """ 注册蓝图 """
    register_blueprints(app)

    """ 注册自定义命令 """
    register_commands(app)
    # 注册 tpc_db_info 的命令
    register_tpc_db_info_commands(app)
    # 注册 flask_sqlalchemy_postgresql_layui 的命令
    register_fspl_commands(app)

    return app


# 注册自定义命令
def register_commands(app):
    @app.cli.command("hello")
    @click.option("--name", default="World", help="The person to greet.")
    def hello(name):
        """Print a greeting message."""
        click.echo(f"Hello, {name}!")

    @app.cli.command("initdb")
    @click.option('--drop', is_flag=True, help='Create after drop.')
    def initdb(drop):
        """Initialize the database."""
        if drop:
            pass
            # 删除所有表
            # db.drop_all()

            # 删除指定表
            # if check_table_exists('user_login'):
            #     UserLogin.__table__.drop(db.engine)
            #     print("user_login表已删除")
        db.create_all()
        click.echo('Initialized database.')

    @app.cli.command("create_tab_info_v")
    def create_tab_info_v():
        """create tab_info_v."""
        base_dir = os.path.dirname(os.path.abspath(__file__))
        print('base_dir = ', base_dir)
        template_folder = os.path.join(base_dir, 'sql', 'create_gauss_table_info_view_p.sql')
        with app.app_context():
            executor = SQLScriptExecutor(db)
            # 替换为你的 SQL 文件路径
            count = executor.execute_sql_file(template_folder)
            print(f"共执行 {count} 条 SQL 语句")
        click.echo('Initialized database.')

    @app.cli.command("execute")
    @click.option("--sql", default="", help="in sql folder.")
    def execute(sql):
        """execute sql file."""
        base_dir = os.path.dirname(os.path.abspath(__file__))
        print('base_dir = ', base_dir)
        template_folder = os.path.join(base_dir, 'sql', sql)
        with app.app_context():
            executor = ExecuteBatchSQLScripts(db)
            executor.execute_sql_file(template_folder)
        click.echo('Initialized database.')


def register_extensions(app):
    """ 注册扩展 """
    db.init_app(app)
    mail.init_app(app)
    # 初始化Mail实例
    # mail = Mail(app)
    scheduler.init_app(app)
    scheduler.start()


def register_blueprints(app):
    """ 注册蓝图 """
    app.register_blueprint(aaa_bp)
    app.register_blueprint(auth_bp)
    app.register_blueprint(tpc_db_info_bp)
    app.register_blueprint(fspl_bp)
    app.register_blueprint(fspl_crud_bp)
    app.register_blueprint(dcs_bp)
    app.register_blueprint(sfat_bp)
    app.register_blueprint(dms_bp)
